<?php
namespace Andorra\dao;

use Andorra\drivers\DataValidator;
use Andorra\exceptions\UnknownEntityTypeException;

class Context {
	private $datasource = null;	
	private $entityTypes = array();
	
	public function __construct() {
		$this->loadConfigFromXml();
	}
	
	public function __get($setName) {
		if (!array_key_exists($setName, $this->entityTypes))
			throw new UnknownEntityTypeException($setName);
		
		return new EntitySet($this->entityTypes[$setName], $this->datasource);
	}
	
	public function insert(Entity $e) {
		$this->datasource->putEntity($e);
	}
	
	private function loadConfigFromXml() {
		$dom = new \DOMDocument('1.0', 'UTF-8');
		$dom->load('xml/andorraconf.xml');
		
		if (!$dom->schemaValidate('xml/andorraconf.xsd'))
			throw new \DOMException('Could not validate andorraconf.xml against the schema!');
		
		// Create datasource
		$driverNodes = $dom->getElementsByTagName('driver');
		$driverNode = $driverNodes->item(0);
		$driverName = 'Andorra\\drivers\\' . $driverNode->getAttribute('name');
		
		$driver = new $driverName($driverNode);
		$this->datasource = new DataValidator($driver);
			
		// Create entity descriptions
		$entityTypes = $dom->getElementsByTagName('entityType');
		
		foreach ($entityTypes as $e) {
			$et = new EntityType($e);
			$this->entityTypes[$et->setName] = $et;
		}
	}
}
?>